package com.liu.my_blog_system.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.regex.Pattern;

/**
 * @author liuchengjie
 */
@Component
public class EmailSender {


    private static String from;

    private static JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    public void setFrom(String username){
        from = username;
    }
    @Autowired
    public void setMailSender(JavaMailSender mailSender){
        EmailSender.mailSender = mailSender;
    }
    //发送简单的文本消息
    public static Boolean sendText(String to,String subject,String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);
        mailSender.send(message);
        return true;
    }

    //发送html类型邮件,context可以传入html类型
    public static Boolean sendHtml(String to, String subject, String context) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(context, true);
        mailSender.send(mimeMessage);
        return true;
    }

    //发送邮件带附件
    public static Boolean sendAttachment(String to, String subject, String context, String filepath) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(context);
        FileSystemResource fileSystemResource = new FileSystemResource(new File(filepath));
        String filename = fileSystemResource.getFilename();
        mimeMessageHelper.addAttachment(filename, fileSystemResource);
        mailSender.send(mimeMessage);
        return true;
    }
    public static boolean isValidEmail(String email) {
        if (!ObjectUtils.isEmpty(email)) {
            return Pattern.matches("\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}", email);
        }
        return false;
    }
}




















